/**
 * Twitter Class - Created by FlashFrameLess Team OCT/2008
 *
 * @author		FabioTNT / FlashFrameLessTeam - http://www.flashframeless.com/
 * @version		1.0
 */

package com.flashframeless.webapis.twitter {
	
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import flash.system.Security;
	
	public class Twitter extends EventDispatcher {
		
		private var _apiKEY			: String;
		private var _apiPOOL		: String;
		private var _loader			: URLLoader;
		private var _xml			: XML;
		private var i				: uint;	
		private var _defaultUser	: String;
		private var _arrPosts		: Array = new Array();
		
		public function Twitter() {
			
			
		}
		
		public function searchPostsByUser( user:String = '' ):void {
			
			if ( user == '' ) {
				
				user = _defaultUser;
				
			}
			
			var url	: String = 'http://www.fabiotnt.com/lab/twitter/twitterProxy.php?userId=fabiotnt';		
			//var url	: String = _apiPOOL + user + '.xml';			
			
			search( url );
			
		}
		
		private function search( url:String ):void {
			
			_loader = new URLLoader();
			
			_loader.addEventListener( Event.COMPLETE, searchComplete );
			_loader.load( new URLRequest( url ) );
			
		}
		
		private function searchComplete( evt:Event ):void {
			
			//Extract data
			_xml = new XML( evt.target.data );
			ParseData( _xml );
			
		}
		
		private function ParseData( data:XML ):void {
			
			_arrPosts = [];
			
			for ( i = 0; i < _xml.status.length(); i++ ) {
				
				var user:Object = {
					
					id:_xml.status[i].user[0].id,
					name:_xml.status[i].user[0].name,
					screen_name:_xml.status[i].user[0].screen_name,
					location:_xml.status[i].user[0].location,
					description:_xml.status[i].user[0].description,
					profile_image_url:_xml.status[i].user[0].profile_image_url,
					url:_xml.status[i].user[0].url,
					protect:_xml.status[i].user[0].protected,
					followers_count:_xml.status[i].user[0].followers_count				
					
				};
				
				_arrPosts.push( {
					
					created_at:_xml.status[i].created_at,
					id:_xml.status[i].id,
					text:_xml.status[i].text,
					source:_xml.status[i].source,
					truncated:_xml.status[i].truncated,
					in_reply_to_status_id:_xml.status[i].in_reply_to_status_id,
					in_reply_to_user_id:_xml.status[i].in_reply_to_user_id,
					user:user,
					url:'http://twitter.com/' + user.screen_name + '/status/' + _xml.status[i].id
					
				} );
				
			}
			
			dispatchEvent( new Event( Event.COMPLETE ) );
			
		}
		
		
		
		public function get arrPosts():Array {
			
			return _arrPosts;
			
		}
		
		public function set key( apiKey:String ):void {
			
			_apiKEY = apiKey;
			
		}
		
		public function set pool( apiPool:String ):void {
			
			_apiPOOL = apiPool;
			
		}
		
		public function set defaultUser( user:String ) {
			
			_defaultUser = user;
			
		}
		
	}
}